#!/usr/bin/python
# -*- coding: UTF-8 -*-
# wanghaiyong 2022-07-02

import serial
import threading
import time
import pyqtgraph as pg

# ECG 频率
FS = 360

#通过串口向板卡模拟发送ECG数据
def sendECGData(ser):
    with open('test_input.txt', 'r') as f:
        for s in f.readlines():
            ser.write(s.encode())
            time.sleep(1.0/FS)

#存储5秒内的ECG数据及识别结果
ay = []
def recvECGData(ser):
    global ay
    len = 5 * FS - 1
    while True:
        if ser.in_waiting:
            str = ser.readline(ser.in_waiting).decode()
            str = str.replace("\n","")
            print(str)
            ay = ay[-len:]
            ay.append(str)

#绘制ECG波形和R峰（红竖线）
p1 = None
def plotData():
    data = []
    i = -22
    pos = []
    for str in ay:
        array = str.split(',')
        signal = int(array[0])
        R = int(array[1])
        i = i + 1
        if R == 1:
            pos.append(i)
        data.append(signal)
    p1.clear()
    p1.plot(data)
    for p in pos:
        p1.addLine(x=p, pen = 'r')

#使用QTimer及pyqtgraph绘制ECG图形
def drawECGData():
    app = pg.QtGui.QApplication([])
    view = pg.GraphicsView()
    l = pg.GraphicsLayout()
    view.setCentralItem(l)
    view.show()
    global p1
    p1 = l.addPlot(title='绘制ECG图形')

    timer = pg.QtCore.QTimer()
    timer.timeout.connect(plotData)
    timer.start(1000)
    app.exec_()

#主入口函数
if __name__ == '__main__':
    #开启串口
    ser = serial.Serial('COM3', 115200, timeout=0.01)

    #开启两个线程，一个是发送模拟的ECG数据，一个是接收ECG数据和识别结果
    t1 = threading.Thread(target=sendECGData, args=(ser,))
    t2 = threading.Thread(target=recvECGData, args=(ser,))
    t1.start()
    t2.start()

    #主线程实时绘制ECG图形
    drawECGData()

